using System;
using GmSm.ScheduleTask;
using Quartz.Impl;
using Quartz;
using System.Threading.Tasks;


namespace GmSm
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.Title = "定时任务（请勿关闭）";
            Console.BackgroundColor = ConsoleColor.Blue;
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "定时任务 开始执行.");

            StdSchedulerFactory factory = new StdSchedulerFactory();
            IScheduler scheduler = await factory.GetScheduler();

            //互联网医监管平台数据上传，每天22点上传
            string time1 = "0 0 22 * * ?";
            await AddJob<Hlwyy_Sdygzx>(scheduler, "job1", "trigger1", time1);
            await scheduler.Start();

            //程序执行立即执行
            await new Hlwyy_Sdygzx().Execute(null);

            do
            {
                if (Console.ReadKey(true).Key == ConsoleKey.F6)
                {
                    return;
                }
                Console.BackgroundColor = ConsoleColor.White;
                Console.ForegroundColor = ConsoleColor.Red;

                Console.WriteLine("程序正在执行，请勿关闭...");

                Console.BackgroundColor = ConsoleColor.Blue;
                Console.ForegroundColor = ConsoleColor.White;
            } while (true);
        }

        /// <summary>
        /// 添加任务
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="scheduler"></param>
        /// <param name="jobName">不要重复</param>
        /// <param name="triggerName">不要重复</param>
        /// <param name="cronExpression">更多参考 https://www.quartz-scheduler.net/documentation/quartz-3.x/tutorial/crontrigger.html#format </param>
        /// <param name="action"></param>
        /// <returns></returns>
        private static async Task AddJob<T>(IScheduler scheduler, string jobName, string triggerName, string cronExpression, Action<SimpleScheduleBuilder> action = null) where T : IJob
        {
            IJobDetail job = JobBuilder.Create<T>()
                .WithIdentity(jobName, "group1")
                .Build();
            ITrigger trigger = null;

            TriggerBuilder tb = TriggerBuilder.Create()
                .WithIdentity(triggerName, "group1")
                .StartNow()
                .WithCronSchedule(cronExpression);

            if (action != null)
            {
                tb = tb.WithSimpleSchedule(action);
            }

            trigger = tb.Build();
            await scheduler.ScheduleJob(job, trigger);
        }

    }
}